package linc.fun.common.rest.http.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yqlin
 * @date 2022/5/5 15:49
 * @description
 */
@Configuration
@ComponentScan("linc.fun.common.rest.http")
@EnableAsync
@EnableAspectJAutoProxy
@EnableConfigurationProperties(TaskThreadPoolConfig.class)
public class RestConfiguration {
    private final TaskThreadPoolConfig threadPoolConfig;

    @Autowired
    public RestConfiguration(TaskThreadPoolConfig threadPoolConfig) {
        this.threadPoolConfig = threadPoolConfig;
    }

    @Bean(name = "async-service")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolConfig.getCorePoolSize());
        executor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveTime());
        executor.setMaxPoolSize(threadPoolConfig.getMaximumPoolSize());
        executor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
        executor.setThreadNamePrefix(threadPoolConfig.getThreadNamePrefix());
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean,使异步线程的销毁优先于Redis等其他处理报错
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        executor.setAwaitTerminationMillis(60);
        executor.initialize();
        return executor;
    }
}
